package com.gooluke.auth.controller;

import com.gooluke.auth.entity.JwtResponse;
import com.gooluke.auth.entity.LoginRequest;
import com.gooluke.auth.service.AuthService;
import com.gooluke.auth.util.JwtUtils;
import jakarta.annotation.Resource;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    AuthService authService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    public ResponseEntity<JwtResponse> login(@RequestBody LoginRequest request) {
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        String token = jwtUtils.generateToken(authenticate);
        redisTemplate.opsForValue().set("jwt:loginlist:" + request.getUsername(), token, 15, TimeUnit.MINUTES);
        return ResponseEntity.ok(new JwtResponse(token));
    }

    @PostMapping("/refresh")
    public ResponseEntity<JwtResponse> refreshToken(@RequestHeader("Authorization") String refreshToken) {
        String newToken = authService.refreshToken(refreshToken.replace("Bearer ", ""));
        return ResponseEntity.ok(new JwtResponse(newToken));
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout(@RequestHeader("Authorization") String token) {
        authService.invalidateToken(token.replace("Bearer ", ""));
        return ResponseEntity.ok().build();
    }
}